<?php

namespace Iwester\Http\Controllers\Admin\Manage;

use Iwester\Http\Controllers\Admin\BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Http\Model\Config\SiteWebColumn;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Config\Banner;


class AdminWebColumnController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * web栏目 列表
     * @return Response
     */
    public function webcolumn(Request $request)
    {
        $webcolumns = SiteWebColumn::with(['subColumn' => function ($query) {
        $query->oldest('sort');
        }])->where('parent_id', 0)->orderBy('sort', 'asc')->get();
        return view('iwester::admin.manage.webcolumn.webcolumn', [
            'webcolumns'=> $webcolumns
        ]);
    }

    /**
     * 添加web栏目
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Request $request, $id=0)
    {
        $parentId = $request->get('parent_id' , 0);
        $webcolumn = $id ? SiteWebColumn::find($id) : false;
        $type = $webcolumn ? $webcolumn->type : 1;
        $parentColumn = $parentId ? SiteWebColumn::find($parentId) : false;
        return view('iwester::admin.manage.webcolumn.edit', [
            'webcolumn'=> $webcolumn,
            'type'=> $type,
            'parentId'=> $parentId,
            'parentColumn'=> $parentColumn,
        ]);
    }

    /**
     * 保存
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            \DB::beginTransaction();
            $id = $request->input('id', 0);
            $params = $request->get('params', []);
            if ($id){
                $siteWebColumn = SiteWebColumn::find($id);
                $siteWebColumn->update($params);
            }else{
                SiteWebColumn::create($params);
            }
            \DB::commit();
            return redirect(route('manage.web_column'));
        } catch (\Exception $e) {
            \DB::rollBack();
            return  redirect()->route('manage.web_column.edit')->with('errors', ['系统错误，保存失败']);
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroy($batch, $id=0)
    {
        try {
            \DB::beginTransaction();
            SiteWebColumn::find($id)->delete();
            \DB::commit();
            return ['code' => 200, 'message' => '删除成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }
}
